<template>
  <div class="crud-page">
    <my-el-card :header="title">
      <div class="toolbar">
        <slot name="query">
          <div class="query">
            <slot name="query-fields"></slot>
            <my-el-button @click="getList" :loading="loading">查询</my-el-button>
            <my-el-button @click="resetQuery">重置</my-el-button>
          </div>
        </slot>
        <div class="actions">
          <my-el-button type="primary" @click="openCreate()">新增</my-el-button>
          <my-el-button type="danger" :disabled="!selection.length" @click="removeSelected">批量删除</my-el-button>
          <slot name="actions"></slot>
        </div>
      </div>

      <my-el-table :data="list" @selection-change="onSelectionChange" v-loading="loading">
        <el-table-column type="selection" width="48" />
        <slot name="columns"></slot>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <my-el-button link type="primary" @click="openEdit(scope.row)">编辑</my-el-button>
            <my-el-button link type="danger" @click="removeRow(scope.row)">删除</my-el-button>
            <slot name="row-actions" :row="scope.row"></slot>
          </template>
        </el-table-column>
      </my-el-table>

      <div class="pager">
        <my-el-pagination
          :current-page="pagination.page"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          layout="prev, pager, next, sizes, jumper"
          @current-change="onPageChange"
          @size-change="onPageSizeChange"
        />
      </div>
    </my-el-card>

    <my-el-dialog v-model="dialogVisible" :title="isEdit ? '编辑' : '新增'" width="520">
      <slot name="form" :model="formModel"></slot>
      <template #footer>
        <my-el-button @click="dialogVisible = false">取消</my-el-button>
        <my-el-button type="primary" :loading="formLoading" @click="submitForm">确定</my-el-button>
      </template>
    </my-el-dialog>
  </div>
</template>

<script setup>
import { toRefs } from 'vue'
import { usePageCrud } from '@/hooks'

const props = defineProps({
  title: { type: String, default: '列表' },
  crud: { type: Object, required: true }
})

// 将传入的 crud 对象解构到模板
const { query, pagination, list, loading, selection, dialogVisible, formModel, formLoading, isEdit } = toRefs(props.crud)
const { getList, resetQuery, openCreate, openEdit, removeRow, removeSelected, onSelectionChange, onPageChange, onPageSizeChange, submitForm } = props.crud
</script>

<style scoped>
.crud-page { padding: 12px; }
.toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; gap: 12px; flex-wrap: wrap; }
.query { display: flex; gap: 8px; align-items: center; }
.pager { display: flex; justify-content: flex-end; margin-top: 12px; }
</style> 